package com.lysj.admin.master.upload.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.lysj.admin.master.common.CommonConstant;
import com.lysj.admin.master.common.exception.BaseException;
import com.lysj.admin.master.common.spring.mpbase.MyService;
import com.lysj.admin.master.common.web.Resp;
import com.lysj.admin.master.upload.domain.UploadInfo;
import com.lysj.admin.master.upload.mapper.UploadInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
@Service
@Transactional
public class UploadService extends MyService<UploadInfoMapper, UploadInfo> {

    public UploadInfo upload(MultipartFile file) {
        return upload(file, null);
    }

    public UploadInfo upload(MultipartFile file, HttpServletRequest request) {
        if (file == null) {
            throw new BaseException(Resp.ResStatus.PARAM_ERROR, "请上传文件");
        }
        String originalName = file.getOriginalFilename();
        String suffix = originalName.substring(originalName.lastIndexOf("."));
        String newName = IdUtil.fastSimpleUUID() + suffix;
        UploadInfo uploadInfo = new UploadInfo();
        if (request != null) {
            Map<String, Object> payloadMap = (Map<String, Object>) request.getAttribute(CommonConstant.JWT_PAYLOAD_KEY);
            if (payloadMap != null) {
                uploadInfo.setOperatorId(payloadMap.get(CommonConstant.JWT_SUB).toString());
            }
        }
        uploadInfo.setFileType(file.getContentType());
        uploadInfo.setFileSize(file.getSize() / 1024);
        uploadInfo.setNewName(newName);
        uploadInfo.setOriginalName(originalName);
        String today = DateUtil.format(new Date(), "yyyy_MM_dd");
        String path = CommonConstant.FILE_PATH + today + CommonConstant.FILE_SEPARATOR;
        if (!FileUtil.exist(path)) {
            FileUtil.mkdir(path);
        }
        File f = new File(path + newName);
        try {
            file.transferTo(f);
            BufferedImage img = ImgUtil.read(f);
            String scalePath = "";
            if (img != null) {
                scalePath = path + CommonConstant.THUMBNAIL + CommonConstant.FILE_SEPARATOR;
                if (!FileUtil.exist(scalePath)) {
                    FileUtil.mkdir(scalePath);
                }
                File tf = new File(scalePath + newName);
                ImgUtil.scale(img, tf, 0.5f);
            }
            uploadInfo.setPath(FileUtil.subPath(CommonConstant.FILE_PATH, f.getAbsolutePath()));
            uploadInfo.setThumbnailPath(FileUtil.subPath(CommonConstant.FILE_PATH, scalePath));
            this.save(uploadInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uploadInfo;
    }

    public void showFiles(HttpServletResponse response,
                          boolean thumbnail, @PathVariable String fileId) throws IOException {
        UploadInfo info = this.getById(fileId);
        if (info == null) {
            return;
        }
        System.out.println("获取类" + info);
        FileInputStream fileIs = null;
        String path = "";
        if (thumbnail) {
            path = CommonConstant.FILE_PATH + info.getThumbnailPath();
        } else {
            path = CommonConstant.FILE_PATH + info.getPath();
        }
        try {
            fileIs = new FileInputStream(path);
        } catch (Exception e) {
            log.error("系统找不到图像文件：" + path);
            return;
        }
        int i = fileIs.available(); //得到文件大小
        byte data[] = new byte[i];
        fileIs.read(data);  //读数据
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(info.getOriginalName(), "UTF-8"));
        OutputStream outStream = response.getOutputStream(); //得到向客户端输出二进制数据的对象
        outStream.write(data);  //输出数据
        outStream.flush();
        outStream.close();
        fileIs.close();
    }

    public String showFile(String id) {
        UploadInfo uploadInfo = this.getById(id);
        if (uploadInfo != null) {
            return uploadInfo.getPath();
        } else {
            return "";
        }
    }

    public List<String> showFiles(String[] ids) {
        List<UploadInfo> uploadInfos = this.listByIds(Arrays.asList(ids));
        List<String> paths = new ArrayList<>(uploadInfos.size());
        for (UploadInfo uploadInfo : uploadInfos) {
            paths.add(uploadInfo.getPath());
        }
        return paths;
    }

    public String showThumbnail(String id) {
        UploadInfo uploadInfo = this.getById(id);
        if (uploadInfo != null) {
            return uploadInfo.getThumbnailPath();
        } else {
            return "";
        }
    }

    public List<String> showThumbnails(String[] ids) {
        List<UploadInfo> uploadInfos = this.listByIds(Arrays.asList(ids));
        List<String> paths = new ArrayList<>(uploadInfos.size());
        for (UploadInfo uploadInfo : uploadInfos) {
            paths.add(uploadInfo.getThumbnailPath());
        }
        return paths;
    }
}
